package com.sneakxy.cloudbase.platform.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sneakxy.cloudbase.platform.bean.Permission;
import com.sneakxy.cloudbase.platform.bean.dto.PermissionDTO;
import com.sneakxy.cloudbase.platform.repository.PermissionRepository;
import com.sneakxy.mybatis.commons.repository.query.domain.CriteriaBuilder;

/**
 * 
 * @author 潜行的青衣
 * @see
 */
@Service
public class PermissionService extends BaseService<Permission, String, PermissionRepository> implements IPermissionService {

	@Autowired
	private IRolePermService rolePermService;
	
	@Autowired
	private IMenuService menuService;
	
	/* (non-Javadoc)
	 * @see com.sneakxy.cloudbase.platform.service.IPermissionService#findAllByParentId(boolean)
	 */
	@Override
	public List<PermissionDTO> findAllByParentId(boolean hasChildren) {
		List<PermissionDTO> result = PermissionDTO.from(getRepository().findAllByParentIdIsNullOrderBySort());
		if(hasChildren) {
			result.forEach((perm) -> {
				perm.setChildren(this.findAllByParentId(perm.getId(), hasChildren));
			});
		}
		return result;
	}
	
	public List<PermissionDTO> findAllByParentId(String parentId, boolean hasChildren) {
		List<PermissionDTO> result = PermissionDTO.from(getRepository().findAllByParentIdOrderBySort(parentId));
		if(hasChildren) {
			result.forEach((perm) -> {
				perm.setChildren(this.findAllByParentId(perm.getId(), hasChildren));
			});
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.cloudbase.platform.service.IPermissionService#countByParentId(java.lang.String)
	 */
	@Override
	public long countByParentId(String parentId) {
		CriteriaBuilder<Permission> builder = new CriteriaBuilder<>(Permission.class);
		builder.andEq("parentId", parentId);
		return this.getRepository().count(builder.build());
	}

	@Override
	@Transactional
	public boolean removeCascad(String id) {
		if(this.countByParentId(id) == 0) {
			rolePermService.deleteByPermId(id);
			menuService.updatePermissionToNull(id);
			delete(id);
			return true;
		}
		return false;
	}
	
}
